var bullseye = [];
var people = [];
var timelineElements = [];
var maxCollabs = 0;
var circleSize = 10;
var textSpace = 18;
var peopleRadius = 0;
var subject;
var subjectIcon;
var subjectLongName;
var currentYear;

function renderTimeline(u) {
	subject = u;

	jQuery.getJSON("functions/dateRange.php?uri="+u,
		function(response){						
			renderTimelineCallback(response);
		}
	);

}

function update(u, y){
	if (u != subject) {
		renderTimeline(u);
	}

	// change date style if neccessary
	for (var yearMarkerIndex in timelineElements) {
		var yearMarker = timelineElements[yearMarkerIndex];
		if (yearMarker.count > 0) {
			yearMarker.attr({fill:"#C6A278"});
			if (yearMarker.year == y) {	
				yearMarker.attr({fill:"#52381D"});
			}
		}		
	}

	subject = u;
	currentYear = y;
	jQuery.getJSON("functions/collabs.php?uri="+u+"&date="+y,
		function(response){						
			updateCallback(response);
		}
	);
}


function renderTimelineCallback(response) {	
	// clear current timeline
	for(var i=0; i<timelineElements.length; i++){
		if(timelineElements[i].text != null){
			timelineElements[i].text.remove();
		}
	timelineElements[i].remove();
	}
	timelineElements = [];

	var minYear = response[0]["year"];
	var maxYear = response[response.length-1]["year"];
	var years = [];

	// if there is no currentYear, set to the max year
	if (currentYear == null) {
		currentYear = maxYear;
	}

	for (var element in response) {
		var year = response[element]["year"];
		var count = response[element]["count"];	
		years[year-minYear] = count;
	}

	var totalYears = maxYear-minYear+1;
	var timelineUnit = timelineLength / totalYears;
	var timelineOriginX = center.x-timelineLength/2;
	var timelineOriginY = timelineOffsetY -timelineHeight;

	var minimalDateWidth = 30;	
	var dateInterval = Math.ceil(minimalDateWidth/timelineUnit);

	for(var i=0; i<totalYears; i++) {
		var yearMarker = raphael.rect(timelineOriginX +i*timelineUnit, timelineOriginY, timelineUnit, timelineHeight);
		yearMarker.year = i+minYear;
		yearMarker.count = years[i];
	
	
		if ((i % dateInterval) == 0) {
			yearMarker.text = raphael.text(yearMarker.attr("x")+timelineUnit/2, yearMarker.attr("y")+timelineHeight+6, yearMarker.year);
			yearMarker.text.attr({"fill":"#52381D"});
		}

		if (yearMarker.count > 0) {
			yearMarker.click (function(event) {
				update(subject, this.year);
			});
		}
		timelineElements.push(yearMarker);	
	}

	update(subject, currentYear);

}


function updateCallback(response) {	

	// to store the current position of the people
	var oldPositions = [];

	// clear current screen
	for(var i=0; i<people.length; i++){
		// store old position
		oldPositions[people[i].uri] = {x:people[i].attr("x"), y:people[i].attr("y"), tx:people[i].text.attr("x"), ty:people[i].text.attr("y")};
		if(people[i].text != null){
			people[i].text.remove();
		}
	people[i].remove();
	}
	people = [];

	// clear the bullseye
	for(var i=0; i<bullseye.length; i++){
		bullseye[i].remove();
	}
	bullseye = [];
	maxCollabs = 0;

	// clear the subject
	if (subjectIcon != null) {
		subjectIcon.remove();
	}

	// add subject
	subjectIcon = raphael.text(center.x, center.y, response["name"]);
	subjectIcon.attr({"font-weight":"bold","fill":"#52381D"});
	subjectLongName = response["longName"];

	$("#titleAreaText").html(subjectLongName +"  " +currentYear);


	// find max collab
	for (var uri in response["people"]) {
		var count = response["people"][uri]["count"];
		if(maxCollabs < count) {
			maxCollabs = count;
		}
	}

	// draw bullseye
	for(var i=0; i<=maxCollabs; i++){
		var closeness = (bullseyeSize/maxCollabs)*i;
		var ring = raphael.circle( center.x, center.y, closeness);
		ring.attr({stroke:"#A5A29A"});
		bullseye.push(ring);
	}

	// add new people
	for (var uri in response["people"]) {
		var name = response["people"][uri]["name"];
		var longName = response["people"][uri]["longName"];
		var count = response["people"][uri]["count"];
		addPerson(uri, name, longName, count);
	}


	// add spacing
	people.sort(function(a,b) { return b.count - a.count; } );

	var used = [];
	var step = people.length;
	var j=0;
	for (var i=0; i<people.length; i++) {	
		var jj = Math.round(j);

		while (used[jj] != null) {
			j = j + step;
			if (j >= people.length) {
				j = 0;
				step = step/2;
			}
			jj = Math.round(j);
		}
		used[jj] = 1;
		people[i].order = jj;
	
	}

	people.sort(function(a,b) { return a.order - b.order; } );	
	
	var animationTime = 1500;

	// position stuff
	for(var i=0; i<people.length; i++){
		var x = Math.sin(i*2*Math.PI/people.length);
		var y = Math.cos(i*2*Math.PI/people.length);

		var closeness = (bullseyeSize/maxCollabs)*(maxCollabs+1-response["people"][people[i].uri]["count"]);

		// check if this person was on the last diagram
		if (oldPositions[people[i].uri] != null) {
			// set to previous position and animate
			people[i].attr({"x": oldPositions[people[i].uri].x, "y": oldPositions[people[i].uri].y});
			people[i].animate({x:(x*closeness+center.x-15), y:(y*closeness+center.y-15)}, animationTime, "<>");
			people[i].text.attr({"x": oldPositions[people[i].uri].tx, "y": oldPositions[people[i].uri].ty});
			people[i].text.animateWith(people[i], {x:(x*closeness+center.x), y:(y*closeness+center.y+textSpace)}, animationTime, "<>");
		}
		else {
			// set to position and fade in
			people[i].attr({x:(x*closeness+center.x-15), y:(y*closeness+center.y-15), opacity:"0"});
			people[i].animate({opacity:"1"}, animationTime, "<>");
			people[i].text.attr({x:(x*closeness+center.x), y:(y*closeness+center.y+textSpace), opacity:"0"});
			people[i].text.animateWith(people[i], {opacity:"1"}, animationTime, "<>");

		}
	
	}
}

function addPerson(uri, name, longName, count){
	var person = raphael.image( "images/person-icon-small.png", 0, 0, 30, 30);
	person.uri = uri;
	person.name = name;
	person.longName = longName;
	person.count = count;

	person.text = raphael.text(0, 0, name);
	person.text.attr({"fill":"#52381D"});

	person.click(function (event) {
		window.longName = this.longName;
		window.uri = this.uri;
		for( var i = 0; i < people.length; i++ ){
			people[i].attr({src:"images/person-icon-small.png"});
		}
		this.attr({src:"images/person-icon-large.png"}); 
		jQuery.getJSON("functions/publications.php?uri="+subject+"&date="+currentYear+"&other="+this.uri,
			function(data){

				var htmlBlock = "";
				htmlBlock += "<h1>Papers co-authored by "+longName+" and " +subjectLongName +" in " +currentYear +".</h1>";
				htmlBlock += "<ol>";				
				for(var i=0; i<data.length; i++){
					htmlBlock += "<li><a href="+data[i].uri+">"+data[i].label+"</a></li>";
				}
				htmlBlock += "</ol>";
				htmlBlock += "<a class='pivot' href='javascript:void(0)' onclick='update(\"" +uri +"\"," +currentYear +")'>Set "+longName +" as Pivot</a>";
				$("#right").html(htmlBlock);

			}
		);
	});

	person.dblclick(function (event) {
		update(person.uri, currentYear);
	});

	people.push(person); 
}

